import { Injectable } from '@angular/core';
import { AppConfig } from "../config";
import { Headers, Http } from '@angular/http';
import { Observable } from "rxjs/Observable";
import { RolePermission } from "../entity/role-permission.model";
import { InterceptorService } from '../service/interceptor/interceptor-service';

@Injectable()
export class RolePermissionService {
  private readonly param = "sysRolePermissions";
  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {
  }
  getPermissions() {
    return this.http.get(`${this.url}`)
      .toPromise()
      .then(response => response.json().data as RolePermission[])
      .catch(this.handleError);
  }
  /**
   * 通过roleId获取RolePermission
   * 
   * @param {number} roleId 
   * @returns {Promise<Permission[]>} 
   * @memberof PermissionService
   */
  getPermissionsByroleID(roleId: number): Promise<RolePermission[]> {
    return this.http.get(`${this.url}/roleId/${roleId}`)
      .toPromise()
      .then(response => response.json().data as RolePermission[])
      .catch(this.handleError);
  }
  create(selectedPermissions): Promise<number> {
    // const url = `http://192.168.15.150:8585/webapi/v1/sysRolePermissions`;
    return this.http
      .post(this.url, JSON.stringify(selectedPermissions))
      .toPromise()
      .then(res => res.json().code)
      .catch(this.handleError);
  }

  batchDelete(valueIds: number[]): Promise<boolean> {
    const apiUrl = `${this.url}?items=${valueIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response.json();
          switch (result.code) {
            case "200":
              return true;
            case "-1":
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }


}



// WEBPACK FOOTER //
// ./src/app/service/role-permission.service.ts